// 应用主逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 初始化Three.js
    initThreeJS();
    animate();
    
    // 初始化模型加载器
    modelLoader = new ModelLoader(scene);
    
    // 绑定事件
    bindEvents();
    
    // 隐藏加载动画
    document.getElementById('loading').style.display = 'none';
});

function bindEvents() {
    // 文件上传
    const fileInput = document.getElementById('file-input');
    const fileName = document.getElementById('file-name');
    
    fileInput.addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            fileName.textContent = file.name;
            loadModel(file);
        }
    });
    
    // 控制按钮
    document.getElementById('reset-view').addEventListener('click', resetView);
    document.getElementById('toggle-rotation').addEventListener('click', toggleRotation);
    document.getElementById('fullscreen').addEventListener('click', toggleFullscreen);
    
    // 拖拽上传
    setupDragAndDrop();
}

function loadModel(file) {
    const loading = document.getElementById('loading');
    loading.style.display = 'block';
    
    modelLoader.loadModel(
        file,
        (progress) => {
            // 进度更新
            console.log(`加载进度: ${Math.round(progress * 100)}%`);
        },
        (error, model) => {
            loading.style.display = 'none';
            
            if (error) {
                alert('模型加载失败: ' + error.message);
                console.error('模型加载错误:', error);
                return;
            }
            
            // 更新全局模型引用
            window.model = model;
            
            // 更新按钮状态
            document.getElementById('toggle-rotation').textContent = '暂停旋转';
            autoRotate = true;
            
            console.log('模型加载成功');
        }
    );
}

function resetView() {
    if (window.model) {
        modelLoader.centerModel(window.model);
    } else {
        // 重置到默认视角
        camera.position.set(0, 2, 5);
        camera.lookAt(0, 0, 0);
        controls.target.set(0, 0, 0);
        controls.update();
    }
}

function toggleRotation() {
    autoRotate = !autoRotate;
    const btn = document.getElementById('toggle-rotation');
    btn.textContent = autoRotate ? '暂停旋转' : '开始旋转';
}

function toggleFullscreen() {
    const container = document.getElementById('canvas-container');
    
    if (!document.fullscreenElement) {
        if (container.requestFullscreen) {
            container.requestFullscreen();
        } else if (container.webkitRequestFullscreen) {
            container.webkitRequestFullscreen();
        } else if (container.msRequestFullscreen) {
            container.msRequestFullscreen();
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

function setupDragAndDrop() {
    const container = document.getElementById('canvas-container');
    
    container.addEventListener('dragover', function(event) {
        event.preventDefault();
        container.style.border = '2px dashed #4CAF50';
    });
    
    container.addEventListener('dragleave', function(event) {
        event.preventDefault();
        container.style.border = 'none';
    });
    
    container.addEventListener('drop', function(event) {
        event.preventDefault();
        container.style.border = 'none';
        
        const files = event.dataTransfer.files;
        if (files.length > 0) {
            const file = files[0];
            const validExtensions = ['.obj', '.fbx', '.gltf', '.glb'];
            const fileExtension = file.name.toLowerCase().substr(file.name.lastIndexOf('.'));
            
            if (validExtensions.includes(fileExtension)) {
                document.getElementById('file-name').textContent = file.name;
                loadModel(file);
            } else {
                alert('请上传有效的3D模型文件（.obj, .fbx, .gltf, .glb）');
            }
        }
    });
}

// 键盘快捷键
document.addEventListener('keydown', function(event) {
    switch(event.key) {
        case 'r':
        case 'R':
            resetView();
            break;
        case ' ':
            event.preventDefault();
            toggleRotation();
            break;
        case 'f':
        case 'F':
            toggleFullscreen();
            break;
    }
});

// 防止右键菜单
document.getElementById('three-canvas').addEventListener('contextmenu', function(event) {
    event.preventDefault();
});
